package com.scs.application.modules.wm.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.consts.GlobalConsts;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.mvc.controller.FlowController;
import com.scs.application.core.query.QueryContext;
import com.scs.application.core.query.QueryContextHolder;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.core.utils.UtilCommon;
import com.scs.application.core.utils.UtilNum;
import com.scs.application.modules.base.entity.Dept;
import com.scs.application.modules.base.entity.ReagentTeam;
import com.scs.application.modules.base.entity.Warehouse;
import com.scs.application.modules.base.mapper.DeptMapper;
import com.scs.application.modules.base.mapper.WarehouseMapper;
import com.scs.application.modules.base.service.MatrService;
import com.scs.application.modules.base.service.ReagentTeamService;
import com.scs.application.modules.purchase.enums.PurchaseType;
import com.scs.application.modules.sys.model.PageResult;
import com.scs.application.modules.sys.model.RestResult;
import com.scs.application.modules.thirdparty.service.MscmService;
import com.scs.application.modules.wm.dto.DeliveryDTO;
import com.scs.application.modules.wm.dto.OrthWiDTO;
import com.scs.application.modules.wm.dto.WorkOrderItemDTO;
import com.scs.application.modules.wm.entity.Transfer;
import com.scs.application.modules.wm.entity.WorkOrder;
import com.scs.application.modules.wm.entity.WorkOrderItem;
import com.scs.application.modules.wm.service.InOrderItemService;
import com.scs.application.modules.wm.service.InOrderService;
import com.scs.application.modules.wm.service.TransferService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 */
@RestController
@RequestMapping("/wm/in_order")
public class InOrderController extends FlowController<InOrderService, WorkOrder> {

    @Autowired
    MscmService mscmService;
    @Autowired
    MatrService matrService;
    @Resource
    TransferService transferService;
    @Resource
    DeptMapper deptMapper;
    @Resource
    WarehouseMapper warehouseMapper;
    @Resource
    InOrderItemService inOrderItemService;
    @Autowired
    private ReagentTeamService reagentTeamService;

    /**
     * 采购入库(采购订单入库)
     * 获取送货单信息
     *
     * @return
     */
    @RequestMapping(value = "/get_delivery", method = RequestMethod.GET)
    public RestResult getDelivery(@RequestParam Map<String, String> reqData) {
        if (StringUtils.isBlank(reqData.get("warehouseId"))) return RestResult.error("未设置入库仓库");
        Map map = service.createWorkOrderByDelivery(reqData.get("asnKey"), reqData.get("warehouseId"), UtilCommon.getStr(reqData.get("deliveryman"), ""), reqData.get("busUser"), UtilNum.getDouble(reqData.get("arrivalTemperature")), "",reqData.get("busType"));
        return RestResult.ok("查询成功", map);
    }

    /**
     * 获取送货单信息(不创建入库单，只是预览）
     *
     * @param asnKey
     * @return
     */
    @GetMapping("/getDelivery")
    public RestResult getDelivery(@RequestParam("asnKey") String asnKey) {
        Map result = new HashMap();
        DeliveryDTO deliveryDTO = mscmService.getDelivery(asnKey);
        result.put("deliver", deliveryDTO);
        result.put("matrs", matrService.getDeliverItemMatr(deliveryDTO.getItems()));
        return RestResult.ok("查询成功", result);
    }

    /**
     * 是否需要调价
     *
     * @param
     * @return
     */
    @PostMapping("/allowAutoAdjust")
    public RestResult allowAutoAdjust(@RequestBody WorkOrder workOrder) {

        return RestResult.ok("查询成功", service.allowAutoAdjust(workOrder));
    }

    /**
     * 是否需要调价
     *
     * @param
     * @return
     */
    @PostMapping("/workOderItemAdjust")
    public RestResult workOderItemAdjust(@RequestBody WorkOrder workOrder) {

        return RestResult.ok("调价成功", service.workOderItemAdjust(workOrder));
    }

    /**
     * 获取送货单信息
     *
     * @param para({asnKey: '',warehouseId: ''})
     * @return
     */
    @PostMapping("/createByAsn")
    public RestResult createWorkOrderByAsn(@RequestBody JSONObject para) {
        if (StringUtils.isBlank(para.getString("warehouseId"))) { return RestResult.error("未设置入库仓库"); }
        Map map = service.createWorkOrderByDelivery(para.getString("asnKey"), para.getString("warehouseId"), null, para.getString("busUser"), UtilNum.getDouble(para.get("arrivalTemperature")), para.getString("reagentTeamId"), null);
        WorkOrder workOrder = (WorkOrder) map.get("workOrder");
        return RestResult.ok("入库单创建成功", workOrder.getId());
    }

    @Override
    @GetMapping("/page")
    public PageResult page() {
        QueryContext queryContext = QueryContextHolder.currentContext();
        queryContext.getWrapper().eq("direction", GlobalConsts.ORDER_DIRECTION_IN);
        IPage pageResult = service.page(queryContext);
        return PageResult.ok("查询成功", pageResult.getRecords(), pageResult.getTotal());
    }

    @GetMapping("/preview")
    public void preview(@RequestParam(name = "workOrderId") String workOrderId,
                        HttpServletResponse response) throws IOException {
        service.preview(workOrderId, response);
    }

    @GetMapping("/isExist")
    public RestResult isExist(@RequestParam("asnKey") String asnKey) {

        RestResult result = service.isExist(asnKey);
        return RestResult.ok("查询成功", result);
    }

    /**
     * 扫描二维码入库
     *
     * @return
     */
    @RequestMapping(value = "/scanQrCode", method = RequestMethod.POST)
    public RestResult scanQrCode(@RequestBody Map para) {
        String warehouseId = para.get("warehouseId").toString();
        String qrCode = para.get("qrCode").toString();
        String inOrderId = para.get("inOrderId").toString();
        if (StringUtils.isBlank(warehouseId)) return RestResult.error("未设置入库仓库");
        if (StringUtils.isBlank(qrCode)) return RestResult.error("二维码信息为空");
        WorkOrder workOrder = service.createWorkOrderByQrCode(warehouseId, qrCode, inOrderId, para.get("deliveryman").toString(), para.get("busUser").toString());
        return RestResult.ok("扫码成功", workOrder);
    }


    /**
     * @Description：手工入库批量操作
     */
    @PostMapping("/saveBatchForInOrder")
    public RestResult saveBatchForInOrder(@Valid @RequestBody List<WorkOrderItemDTO> entityList) {
        service.saveBatchForInOrder(entityList);
        return RestResult.ok("批量添加成功",  entityList);
    }

    @RequestMapping(value = "/orth_wi_notify", method = RequestMethod.POST)
    public RestResult orthWiNotify(@Valid @RequestBody OrthWiDTO orthWiDTO) {
        return service.createWorkOrderByOrthScan(orthWiDTO);
    }


    /**
     * 根据订单一键配送/调拨至检验科冷链库或专业组
     *
     * @param workOrder
     */
    @PostMapping("/autoResponse")
    public RestResult autoResponse(@RequestBody WorkOrder workOrder) {
        if (PurchaseType.REAGENT.getKey().equals(workOrder.getPurchaseOrderType())) {
            if (StringUtils.isNotEmpty(workOrder.getDeptId())) {
                Dept dept = deptMapper.selectById(workOrder.getDeptId());
                if (StringUtils.isNotEmpty(dept.getWarehouseId())) {
                    Warehouse warehouse = warehouseMapper.selectById(dept.getWarehouseId());
                    if (warehouse.getFlagCenter()) {
                        throw new BusinessException(String.format("需求科室[%s]关联的仓库[%s]是中心仓库，不支持一键配送试剂，请手工创建配送单！", dept.getName(), warehouse.getName()));
                    }
                }
            }
            Map<String, String> ids = new HashMap<>();
            // 试剂全部走调拨，是否库存试剂决定出库结算还是用后结算
            Transfer transfer = transferService.autoChangeTransfer(workOrder);
            ids.put("transferId", transfer.getId());
            return RestResult.ok("转换成功", ids);
        }
        return RestResult.error();
    }


    private void fillEntity(WorkOrder entity) {
        if (StringUtils.isNotBlank(entity.getReagentTeamId())) {
            ReagentTeam reagentTeam =reagentTeamService.getById(entity.getReagentTeamId());
            if (reagentTeam != null) {
                entity.setReagentTeamName(reagentTeam.getName());
            }
        }

        entity.setCountDtl(inOrderItemService.count(Wrappers.<WorkOrderItem>query().select("id").eq("work_order_id",entity.getId())));
    }


    /**
     * 根据ID查找数据
     */
    @GetMapping("/find")
    public RestResult find(@RequestParam("id") Serializable id) {
        WorkOrder entity = service.getById(id);
        if (entity == null) {
            return RestResult.error("数据查询失败<br>可能所操作数据已被删除，请刷新后重新尝试操作");
        }
        fillEntity(entity);
        return RestResult.ok("获取数据成功", entity);
    }


    /**
     * 添加/更新数据
     */
    @PostMapping("/save")
    public RestResult saveItem(@Valid @RequestBody WorkOrder entity) {
        boolean isOk = service.saveOrUpdate(entity);
        if (!isOk) {
            return RestResult.error("数据保存失败");
        }
        fillEntity(entity);
        return RestResult.ok("数据保存成功", entity);
    }

}
